using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseRead.API.Applications.Commands.Departments;
using ContentmanagementBaseRead.API.Dtos;
using MediatR;
using AutoMapper;
using Microsoft.EntityFrameworkCore;

namespace ContentmanagementBaseRead.API.Applications.Commandhandlters.Departments
{
    /// <summary>
    /// 获取一级科室信息列表命令处理
    /// </summary>
    public class GetFirstLevelDepartmentsCommandHandler : IRequestHandler<GetFirstLevelDepartmentsCommand, ApiPaging<List<DepartmentDtos>>>
    {
        /// <summary>
        /// 科室仓储
        /// </summary>
        private readonly IBaseRepository<DepartmentManagementModel> _departmentRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<GetFirstLevelDepartmentsCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository">科室仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志</param>
        public GetFirstLevelDepartmentsCommandHandler(
            IBaseRepository<DepartmentManagementModel> departmentRepository,
            IMapper mapper,
            ILogger<GetFirstLevelDepartmentsCommandHandler> logger)
        {
            _departmentRepository = departmentRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取一级科室列表命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<ApiPaging<List<DepartmentDtos>>> Handle(GetFirstLevelDepartmentsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理一级科室查询命令，页码：{PageIndex}，每页数量：{PageSize}", 
                    request.PageIndex, request.PageSize);

                // 获取所有一级科室数据（ParentId = 0）
                var query = _departmentRepository.GetAll().AsNoTracking();
                   

                /// 判断是否指定父级ID
                if(request.ParendId == 0)
                {

                    query = query.Where(x => x.ParentId ==0);

                }
                else
                {

                   query = query.Where(x => x.ParentId == request.ParendId);

                }


                // 按创建时间倒序排列
                query = query.OrderByDescending(x => x.CreatedTime);

                // 获取总数量
                var totalCount = query.Count();
            

                // 计算分页信息
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);
                var skip = (request.PageIndex - 1) * request.PageSize;
                // 获取分页数据
                var pagedData = query.Skip(skip).Take(request.PageSize).ToList();
       
                // 映射到DTO
                var departmentDtos = _mapper.Map<List<DepartmentDtos>>(pagedData);

                return new ApiPaging<List<DepartmentDtos>>
                {
                    code = ResultEnumCode.Ok,
                    message = "科室列表获取成功",
                    data = departmentDtos,
                    TotalCount = totalCount,
                    PageCount = pageCount,
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取科室列表过程中发生异常，页码：{PageIndex}，每页数量：{PageSize}", 
                    request.PageIndex, request.PageSize);

                return new ApiPaging<List<DepartmentDtos>>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取科室列表失败：{ex.Message}",
                    data = new List<DepartmentDtos>(),
                    TotalCount = 0,
                    PageCount = 0,
                };
            }
        }
    }
} 